var system = require('system');
var url  = system.args[4];
var dir  = system.args[5];
url = url || '';
dir = dir || 'files/';
file = encodeURIComponent(url);

console.log(url + ' started.');

var casper = require('casper').create({
        "pageSettings" : {
            loadImages: false,
            loadPlugins: false,
            javascriptEnabled: true,
            localToRemoteUrlAccessEnabled: false,
            resourceTimeout: 5000
        },
        timeout: 20000,
        logLevel: "error",//日志等级
        verbose: true,    // 记录日志到控制台
        onLoadError: function(casper, url, status) {
            this.echo(url + "===>loadError error " + status);
            casper.exit();
        },
        httpStatusHandlers: {
            404: function(self, resource) {
                self.echo(resource.url + ' not found waring STATUS_ERROR (404)');
                casper.exit();
            },
            500: function(self, resource) {
                self.echo(resource.url + ' gave an error STATUS_ERROR (500)');
                casper.exit();
            },
            200: function(self, resource) {
                if(url != resource.url) {
                    self.echo(resource.url + ' gave an error STATUS_ERROR (200)');
                    casper.exit();
                }
            }
        }
});

casper.on('timeout', function () {
    this.echo(this.getCurrentUrl().trim() + " error ===>timeout");
    casper.exit();
});

casper.on('resourceTimeout', function () {
    this.echo(this.getCurrentUrl().trim() + " error ===>resourceTimeout");
    casper.exit();
});

casper.start(url, function(){
    
});

casper.run(function () {
    this.download(url, dir + file);
    this.echo(dir + file + ' saved success');
    casper.exit();
});